package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.form.FormInstanceDto;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.form.FormInstanceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowFormInstanceRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowFormInstance;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowFormInstanceExample;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowFormInstanceDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author lilh
 * @date 2021/3/4 11:15
 */
@Slf4j
@Repository
public class FlowFormInstanceRepositoryImpl implements FlowFormInstanceRepository {

    @Autowired
    private FlowFormInstanceDAO formInstanceDAO;

    @Override
    public boolean insertFormInstance(FormInstanceDto formInstance) {
        FlowFormInstance entity = new FlowFormInstance();
        entity.setProcessInstanceId(formInstance.getProcessInstanceId());
        entity.setTaskId(formInstance.getTaskId());
        entity.setResource(JSONObject.toJSONString(formInstance.getResource()).getBytes(StandardCharsets.UTF_8));
        return formInstanceDAO.insertSelective(entity) > 0;
    }

    @Override
    public FormInstanceVo getFormInstance(String processInstance, String taskId) {
        Assert.isFalse(Objects.isNull(processInstance) && Objects.isNull(taskId));

        FlowFormInstanceExample condition = new FlowFormInstanceExample();
        FlowFormInstanceExample.Criteria criteria = condition.createCriteria();
        if (Objects.nonNull(processInstance)) {
            criteria.andProcessInstanceIdEqualTo(processInstance);
        }

        if (Objects.nonNull(taskId)) {
            criteria.andTaskIdEqualTo(taskId);
        } else {
            criteria.andTaskIdIsNull();
        }
        List<FlowFormInstance> flowFormInstances = formInstanceDAO.selectByExampleWithBLOBs(condition);
        if (flowFormInstances.size() > 0) {
            return convert(flowFormInstances.get(0));
        }
        return null;
    }

    private FormInstanceVo convert(FlowFormInstance entity) {
        if (Objects.isNull(entity)) {
            return null;
        }
        FormInstanceVo result = new FormInstanceVo();
        result.setId(entity.getId());
        result.setProcessInstanceId(entity.getProcessInstanceId());
        result.setTaskId(entity.getTaskId());
        result.setValues(JSONObject.parseObject(new String(entity.getResource())));
        return result;
    }
}
